# -*- coding: utf-8 -*-
"""
Created on Mon Feb  6 22:43:49 2023

@author: TANGLI
"""

import time
import json
import pandas as pd
from get_resp import get_resp
from bs4 import BeautifulSoup

class Fol(object):
    
    def __init__(self):
        self.get_resp = get_resp
    
    def get_fund_info(self, url: str , fund_field):
        with self.get_resp(url) as resp:
            data = resp.json()
            data = [[row.get('cell').get(key) for key in fund_field.keys()] for row in data.get('rows')]
            df = pd.DataFrame(columns=fund_field.values(),data=data) 
        return df
    
    def df_transfrom(self, df, columnAs, columnBs):
        for column in columnAs:
            df.loc[df[column].isin(['-','']),column] = '0'
            df[column] = df[column].astype(float)
        df = df[df['成交(万元)']>=15]
        for column in columnBs:
            df.loc[df[column].isin(['-','']),column] = '0'
            df.loc[:,column] = df.apply(lambda r: float(r[column].split('%')[0]), axis=1)
        return df

    def func_algorithm(self, df, premium_rate, percent):
        if df[premium_rate] > 0 and (df[premium_rate] - df['申购费'] > percent):
            return f"申购：{str(round(df[premium_rate] - df['申购费'],2))}"
        elif df[premium_rate] < 0 and (abs(df[premium_rate]) - df['赎回费'] > percent):
            return f"赎回：{str(round(abs(df[premium_rate]) - df['赎回费'],2))}"
        
    def sort_columns(self, df):
        columns = df.columns.tolist()
        item = columns.pop()
        columns.insert(0, item)
        return df[columns]
                
    def handle_fol_info(self):
        pass

    def query_fund_status(self, code: str):
        url = f"http://fund.eastmoney.com/{code}.html?spm=search"
        resp = self.get_resp(url)
        soup = BeautifulSoup(resp.content,'html.parser')
        labels = soup.find_all('span', class_='staticCell')
        purchase = labels[0].text
        purchase = purchase.split("(")[0]
        return purchase.strip()
    
class FolInteral(Fol):
    
    def __init__(self):
        Fol.__init__(self)
       
    def handle_fol_info(self):
        timeStamp = int(time.time())
        urls =  [f'https://www.jisilu.cn/data/lof/stock_lof_list/?___jsl=LST___t={timeStamp}&rp=25&page=1', 
                 f'https://www.jisilu.cn/data/lof/index_lof_list/?___jsl=LST___t={timeStamp}&only_owned=&rp=25']
        fund_field = {'fund_id': '代码',
                      'fund_nm': '名称',
                      'price': '现价',
                      'increase_rt': '涨幅',
                      'volume': '成交(万元)',
                      'amount': '场内份额(万份)',
                      'discount_rt': '溢价率',
                      'apply_fee': '申购费',
                      'redeem_fee': '赎回费'}     
        dfs = [self.get_fund_info(url, fund_field) for url in urls]
        df_concat = pd.concat(dfs)
        df_concat = self.df_transfrom(df_concat, 
                                ['现价', '涨幅', '成交(万元)', '溢价率'],
                                ['申购费', '赎回费'])
            
        df_concat.loc[:,'操作'] = df_concat.apply(self.func_algorithm, premium_rate='溢价率', percent=0.4, axis=1)
        df_concat = df_concat.loc[-df_concat.操作.isna()]
        df_concat = df_concat.reset_index()
        df_concat.drop(['index','申购费','赎回费'],axis=1,inplace=True)
        df_concat = self.sort_columns(df_concat)
        return df_concat.to_json()

class FolQdiiEur(Fol):
    
    def __init__(self):
        Fol.__init__(self)
      
    def handle_fol_info(self):
        timeStamp = int(time.time())
    
        urls = [f'https://www.jisilu.cn/data/qdii/qdii_list/E?___jsl=LST___t={timeStamp}&rp=22&page=1',
                f'https://www.jisilu.cn/data/qdii/qdii_list/C?___jsl=LST___t={timeStamp}&rp=22&page=1']
        
        fund_field = {'fund_id': '代码', 
                      'fund_nm': '名称', 
                      'price': '现价', 
                      'increase_rt': '涨幅', 
                      'volume': '成交(万元)', 
                      'amount': '场内份额(万份)', 
                      'ref_increase_rt': 'T-1指数涨幅', 
                      'discount_rt': 'T-1溢价率', 
                      'apply_fee': '申购费', 
                      'redeem_fee': '赎回费'} 
        
        dfs = [self.get_fund_info(url, fund_field) for url in urls]
        df_concat = pd.concat(dfs)
        df_concat = self.df_transfrom(df_concat, 
                                ['现价', '成交(万元)'],
                                ['涨幅','T-1指数涨幅','T-1溢价率', '申购费', '赎回费'])
            
        df_concat.loc[:,'操作'] = df_concat.apply(self.func_algorithm, premium_rate='T-1溢价率', percent=2.0, axis=1)
        df_concat = df_concat.loc[-df_concat.操作.isna()]
        df_concat = df_concat.reset_index()
        df_concat.drop(['index','申购费','赎回费'],axis=1,inplace=True)
        df_concat = self.sort_columns(df_concat)
        return df_concat.to_json()
       
class FolQdiiAsia(Fol):
    
    def __init__(self):
        Fol.__init__(self)
                      
    def handle_fol_info(self):
        timeStamp = int(time.time())
        url = f'https://www.jisilu.cn/data/qdii/qdii_list/A?___jsl=LST___t={timeStamp}&rp=22&page=1'
        fund_field = {'fund_id': '代码', 
                    'fund_nm': '名称', 
                    'price': '现价', 
                    'increase_rt': '涨幅', 
                    'volume': '成交(万元)', 
                    'amount': '场内份额(万份)', 
                    'ref_increase_rt': '指数涨幅', 
                    'discount_rt': '溢价率', 
                    'apply_fee': '申购费', 
                    'redeem_fee': '赎回费'} 
        
        df_concat = self.get_fund_info(url, fund_field)
        df_concat = self.df_transfrom(df_concat, 
                                ['现价', '成交(万元)'],
                                ['涨幅','指数涨幅','溢价率', '申购费', '赎回费'])
        df_concat.loc[:,'操作'] = df_concat.apply(self.func_algorithm, premium_rate='溢价率', percent=1.0, axis=1)
        df_concat = df_concat.loc[-df_concat.操作.isna()]
        df_concat = df_concat.reset_index()
        df_concat.drop(['index','申购费','赎回费'],axis=1,inplace=True)
        df_concat = self.sort_columns(df_concat)
        return df_concat.to_json()
    
class FolHistory:

    def __init__(self, code: str):
        self.code = code
        self.get_resp = get_resp

    def fitch_data(self):
        timeStamp = int(time.time()*1000)
        url = f"https://www.jisilu.cn/data/lof/hist_list/{self.code}?___jsl=LST___t={timeStamp}"
        with self.get_resp(url) as resp:
            data = resp.json()
            data = [[row.get('cell').get(key) for key in ['price_dt','price','net_value','discount_rt']] for row in data.get('rows')]
        return json.dumps(dict(data=data))